package com.zhoukai.business.service.license;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.zhoukai.business.util.license.LicenseContent;
import com.zhoukai.business.util.license.LicenseContentManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * author:zkai
 * date: 2024/1/31 15:15
 * description: 在项目启动时安装证书
 * version:1.0
 */
@Component
@Slf4j
public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
    private volatile boolean isExecuted = false; // 标志位，用于判断是否已经执行过

    @Value("${license.secretKey}")
    private String secretKey;

    @Autowired
    LicenseVerify licenseVerify;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (!isExecuted) {
            Resource resource = null;
            try {
                resource = new ClassPathResource("license.lic");
            } catch (Exception e) {
                log.error("读取证书异常", e);
                throw new RuntimeException("证书不存在！请联系管理员");
            }
            log.info("++++++++ 开始安装证书 ++++++++");
            // 获取文件内容
            String readString = resource.readStr(StandardCharsets.UTF_8);
            LicenseContent licenseContent = LicenseContentManager.instance(readString, secretKey);
            licenseVerify.verify();
            log.info("++++++++ 证书安装结束 ++++++++ 证书有效时间 {} -------> {}", licenseContent.getIssuedTime(), licenseContent.getExpiryTime());

            isExecuted = true; // 将标志位设置为已执行
        }
    }
}
